package cn.chinasyq.photoquan.user.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;

import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.user.bean.GameOrder;
import cn.chinasyq.photoquan.user.mode.Result;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.chinasyq.photoquan.util.FormatUtil;
import cn.chinasyq.photoquan.view.SweetAlertDialog.SweetAlertDialog;
import cn.chinasyq.photoquan.wxapi.WXPayEntryActivity;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;

public class PaymentGameActivity extends Activity implements View.OnClickListener, ResponseHandler.OnSucceedListener, ResponseHandler.OnNeedLoginListener, ResponseHandler.OnFailedListener {
    private static final String TAG_PAY_ALIPAY = "alipay";
    private GameOrder order;

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        if (tag.equals(TAG_PAY_ALIPAY)) {
            pay_zhifubao((String) data);
        }
    }

    @Override
    public void onNeedLogin(String tag) {

    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {

    }

    public enum PayMode {
        zhifubao
    }

    private PayMode payMode = PayMode.zhifubao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_payment);
        order = (GameOrder) getIntent().getExtras().get(GameOrder.class.getSimpleName());
        initView();
        initData();
    }

    public void payGame() {
        ResponseHandler handler = new ResponseHandler(TAG_PAY_ALIPAY);
        handler.setOnSucceedListener(this);
        handler.setOnNeedLoginListener(this);
        handler.setOnFailedListener(this);
        UserMode.payGame(order.getUuid(), UserMode.getCurrentUserInfo(this).getToken(), "GamePhoto", handler);
    }

    private void initData() {
        check_zhifubao();
    }

    private void initView() {
        findViewById(R.id.ibtn_back).setOnClickListener(this);
        TextView tv_price = (TextView) findViewById(R.id.tv_price);
        tv_price.setText("￥" + FormatUtil.obtainShopPriceFormat(order.getTotal_fee()));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (WXPayEntryActivity.weixinPaySuccessed) {
            WXPayEntryActivity.weixinPaySuccessed = false;
            setResult(RESULT_OK, (getIntent()));
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_back:
                finish();
                break;
            case R.id.layout_weixin:
//                payMode = PayMode.weixin;
//                pay();
                break;
            case R.id.layout_zhifubao:
                payMode = PayMode.zhifubao;
                payGame();
                break;
            case R.id.layout_yinlian:
//                payMode = PayMode.yinlian;
//                pay();
                break;
            default:
                break;
        }
    }

    private void pay(String var1) {
        switch (payMode) {
//            case weixin: {
//                new ShopWeixinPayDialog(this, SweetAlertDialog.PROGRESS_DEFAULT_TYPE).setData(orderDetailsBean.getUuid());
//            }
//            break;
            case zhifubao: {
                pay_zhifubao(var1);
            }
            break;
//            case yinlian: {
//                new ShopYinlianPayDialog(ShopPaymentActivity.this, SweetAlertDialog.PROGRESS_DEFAULT_TYPE).setData(orderDetailsBean.getUuid());
//            }  break;
            default:
                break;
        }
    }

    /**
     * 支付宝支付逻辑
     */
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;
    /**
     * 是否使用客户端支付
     */
    private boolean canAppPay;

    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    Result resultObj = new Result((String) msg.obj);
                    String resultStatus = resultObj.resultStatus;

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtil.showTips(PaymentGameActivity.this, R.mipmap.tips_smile, getString(R.string.pay_for_success));
                        setResult(RESULT_OK, getIntent());
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”
                        // 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showTips(PaymentGameActivity.this, R.mipmap.tips_smile, getString(R.string.pay_as_a_result_confirmed));
                            setResult(RESULT_OK, getIntent());
                            finish();
                        } else {
                            ToastUtil.showTips(PaymentGameActivity.this, R.mipmap.tips_smile, getString(R.string.pay_for_failure));
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    canAppPay = (Boolean) msg.obj;
                    // Toast.makeText(PayActivity.this, "检查结果为：" + msg.obj,
                    // Toast.LENGTH_SHORT).show();
                    Log.e("zhifubao,,,", "paymode = " + canAppPay);
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     *
     * @param var1
     */
    public void pay_zhifubao(final String var1) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PaymentGameActivity.this);
                // 调用支付接口
                String result = alipay.pay(var1
                );
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * check whether the device has authentication alipay account.
     * 查询终端设备是否存在支付宝认证账户
     */
    public void check_zhifubao() {
        Runnable checkRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask payTask = new PayTask(PaymentGameActivity.this);
                boolean isExist = payTask.checkAccountIfExist();
                Message msg = new Message();
                msg.what = SDK_CHECK_FLAG;
                msg.obj = isExist;
                mHandler.sendMessage(msg);
            }
        };

        Thread checkThread = new Thread(checkRunnable);
        checkThread.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (data == null) {
            return;
        }

        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            setResult(RESULT_OK, getIntent());
            finish();
            return;
        } else if (str.equalsIgnoreCase("fail")) {
            msg = getString(R.string.pay_for_failure);
            new SweetAlertDialog(this).setTitleText(msg).setConfirmText("")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    }).showCancelButton(false).show();
        } else if (str.equalsIgnoreCase("cancel")) {
        }
    }
}
